package com.hqq.helper;

import com.hqq.util.ConfigUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * DBHelper
 * 数据库操作类
 * Created by heqianqian on 2017/7/22.
 */
public class DBHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(DBHelper.class);

    /**
     * 定义一个用于防止数据库连接的局部线程变量[使每个线程都有一个连接]
     */
    private static ThreadLocal<Connection> connContainer = new ThreadLocal<>();

    /**
     * 获取数据库连接
     *
     * @return Connection
     */
    public static Connection getConnection() {
        Connection connection = connContainer.get();
        try {
            if (connection == null) {
                Class.forName(ConfigUtil.getDBDriver());
                connection = DriverManager.getConnection(ConfigUtil.getDBUrl(), ConfigUtil.getDBUser(), ConfigUtil.getDBPassword());
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            connContainer.set(connection);
        }
        return connection;
    }

    /**
     * 关闭连接
     */
    public static void closeConnection() {
        Connection connection = connContainer.get();
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            connContainer.remove();
        }
    }

    /**
     * 开启事务
     */
    public static void beginTransaction() {
        Connection connection = getConnection();
        try {
            if (connection != null) {
                connection.setAutoCommit(false);//关闭自动提交
            }
        } catch (SQLException e) {
            LOGGER.error("begin transaction");
            throw new RuntimeException(e);
        } finally {
            connContainer.set(connection);
        }
    }

    /**
     * 提交事务
     */
    public static void commitTransaction() {
        Connection connection = getConnection();
        if (connection != null) {
            try {
                connection.commit();
                connection.close();
            } catch (SQLException e) {
                LOGGER.error("commit transaction");
                throw new RuntimeException(e);
            } finally {
                connContainer.remove();
            }
        }
    }

    /**
     * 回滚事务
     */
    public static void rollbackTransaction() {
        Connection connection = getConnection();
        if (connection != null) {
            try {
                connection.rollback();
                connection.commit();
            } catch (SQLException e) {
                LOGGER.error("rollback transaction");
                throw new RuntimeException(e);
            } finally {
                connContainer.remove();
            }
        }
    }

}














